package com.own.core.html.panel.dropdown;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.wicket.model.ResourceModel;

import com.own.core.html.form.dropDown.DropDown;
import com.own.core.html.form.dropDown.OwnChoiceRenderer;

import com.own.core.html.form.dropDown.OwnDropDown;
import com.own.core.html.panel.OwnDynPanel;
import com.own.util.model.OwnCompoundPropertyModel;
import com.own.core.operation.DbOperation;

public class OwnDropDownPan extends OwnDynPanel {

	DropDown dropDown;

	public OwnDropDownPan(OwnCompoundPropertyModel model, Field field,
			DropDown dropDownAn) {
		super(model, field);
		this.dropDown = dropDownAn;
		List obj = null;
		OwnChoiceRenderer choiceRenderer = null;
		String resourceName = field.getDeclaringClass().getSimpleName() + "."
				+ field.getName();

		if (dropDown.lazy()) {
			obj = new ArrayList();
			try {
				field.setAccessible(true);
				obj.add(field.get(model.getObject()));
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (field.getType().isEnum()) {
			obj = Arrays.asList(field.getType().getEnumConstants());
			choiceRenderer = new OwnChoiceRenderer(dropDownAn.property(),
					"name");
		} else if (!dropDown.NamedQuery().equals("")) {
			obj = DbOperation.getME().executeNamedQuery(dropDown.NamedQuery());

		} else {
			obj = DbOperation.getME().listAll(field.getType());

		}

		if (choiceRenderer == null) {

			choiceRenderer = new OwnChoiceRenderer("name", "id");
		}
		OwnDropDown dropDown = new OwnDropDown("select", model.bind(field
				.getName()), obj, choiceRenderer, this.dropDown);

		dropDown.setField(field);
		this.setFormComponent(dropDown);
		draw();

	}

	public DropDown getDropDown() {
		return dropDown;
	}

	public void setDropDown(DropDown dropDown) {
		this.dropDown = dropDown;
	}

}
